package cn.cdu.medical.service.impl;

import cn.cdu.basics.utils.SecurityUtil;
import cn.cdu.medical.entity.ChatMessage;
import cn.cdu.medical.dto.ConsultationIdWithTime;
import cn.cdu.medical.mapper.ChatMessageMapper;
import cn.cdu.medical.service.ChatMessageService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;

@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {

    private static final Logger log = LoggerFactory.getLogger(ChatMessageServiceImpl.class);

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Override
    public List<ChatMessage> getMessagesByConsultationId(String consultationId) {
        return baseMapper.getMessagesByConsultationId(consultationId);
    }

    @Override
    public List<ConsultationIdWithTime> getRecentConsultationIds(String userId, int limit) {
        return baseMapper.getRecentConsultationIds(userId, limit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveMessage(ChatMessage message) {
        if (message.getCreateTime() == null) {
            message.setCreateTime(LocalDateTime.now());
        }
        
        try {
            if (securityUtil.getCurrUser() != null && message.getUserId() == null) {
                message.setUserId(Long.valueOf(securityUtil.getCurrUser().getId()));
            }
        } catch (Exception e) {
            // 忽略未登录异常
        }
        
        return save(message);
    }

    @Override
    public Map<String, List<ChatMessage>> getAllUserConsultations(String userId) {
        // 获取用户的所有消息
        List<ChatMessage> messages = chatMessageMapper.getMessagesByUserId(userId);
        log.info("Found {} messages for user {}", messages.size(), userId);
        
        // 按咨询ID分组
        Map<String, List<ChatMessage>> consultations = messages.stream()
            .collect(Collectors.groupingBy(ChatMessage::getConsultationId));
        log.info("Grouped messages into {} consultations", consultations.size());
        
        return consultations;
    }
} 